package com.cruise.game.security.service;

import com.cruise.game.common.enums.RoleEnum;
import com.cruise.game.common.enums.UserStatusEnum;
import com.cruise.game.mapper.UserMapper;
import com.cruise.game.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户详情服务实现
 *
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        User user = userMapper.selectByOpenid(username);
        if (user == null) {
            log.error("用户不存在: {}", username);
            throw new UsernameNotFoundException("用户不存在");
        }

        // 账号状态验证
        if (!UserStatusEnum.isActive(user.getStatus())) {
            log.error("用户已被禁用: {}", username);
            throw new UsernameNotFoundException("用户已被禁用");
        }

        // 设置角色权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(RoleEnum.getRoleCode(user.getRole())));

        // 返回UserDetails
        return new org.springframework.security.core.userdetails.User(
                user.getOpenid(),
                user.getOpenid(), // 微信登录不需要密码，这里使用openid替代
                true,
                true,
                true,
                true,
                authorities
        );
    }
}
